import java.util.Hashtable;
import java.io.FileReader;
import java.io.BufferedReader;

public class WordDictionary {
	Hashtable<Object, Object> m_table;
	String m_LastWord;
	
	WordDictionary(){
		m_table = new Hashtable<Object, Object>();
		LoadFile("dictionary.txt");
	}

	public void LoadFile(String filename){
		try{
			FileReader ifr = new FileReader(filename);
			BufferedReader bfr= new BufferedReader(ifr);
			
			String line = "";
            while ( line != null )
            {
            	line = bfr.readLine();
            	if (line != null){
            		m_table.put(line.trim(), line.trim());
            	}
            }
            
            bfr.close();
            ifr.close();
		}
		
		catch (Exception e){
			System.out.println("Could not read dictionary file");
			System.exit(1);
		}
	}
	
	public boolean WordExists(String word){
		word = word.toLowerCase();
		if (m_table.get(word) != null)
			return true;
		
		return false;
	}
	
	public int EnumerateClosestWords(String scrambled, String word, int index, boolean changed){
		if (scrambled.length()>18)
			return 0;
		
		if (index== scrambled.length()){
			if (changed && WordExists(word)){
				m_LastWord = word;
				return 1;
			}
			else{
				return 0;
			}
		}
		
		char ch = scrambled.charAt(index);
		if ( (ch>='A' && ch <='Z') || (ch>='a' && ch <='z'))
			return  EnumerateClosestWords(scrambled, word+ch, index+1, changed);
		
		char i;
		int sum=0;

		for (i='a'; i<='z'; i++){
			sum += EnumerateClosestWords(scrambled, word+i, index+1, true);
		}
		
		return sum;
	}
	
	public int OneLetterWrong(String word){
		int i, j, sum=0;
		String fixed;
		char[] arr = new char[word.length()]; 
		word.getChars(0, word.length(), arr, 0);
		
		for (i=0; i<word.length(); i++){
			fixed = "";
			for (j=0; j<word.length(); j++){
				if (j==i)
					fixed += '*';
				else
					fixed += arr[j];
			}
			sum += EnumerateClosestWords(fixed, "", 0, false);
		}
		
		return sum;
	}
	
	public static boolean OnlyLetters(String word){
		int i;
		char ch;
		for (i=0; i<word.length(); i++){
			ch = word.charAt(i);
			if ( !(ch>='a' && ch<='z') && !(ch>='A' && ch<='Z' && (i==0 || word.charAt(0)<'a')) )
				return false;
		}
		
		return true;
	}
	
	public static boolean OnlyCapitals(String word){
		int i;
		char ch;
		for (i=1; i<word.length(); i++){
			ch = word.charAt(i);
			if ( !(ch>='A' && ch<='Z') )
				return false;
		}
		
		return true;
	}
	
	public static boolean HasCapitals(String word){
		int i;
		char ch;
		for (i=1; i<word.length(); i++){
			ch = word.charAt(i);
			if ( (ch>='A' && ch<='Z') )
				return true;
		}
		
		return false;
	}
}
